package com.i2works.smartluolong.api.controller.index;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.i2works.smartluolong.api.utils.BaseModule;
import com.i2works.smartluolong.utils.base.DateConstant;
import com.i2works.smartluolong.utils.base.GlobalConstant;
import com.i2works.smartluolong.utils.common.DateUtils;
import com.i2works.smartluolong.utils.entity.R;
import com.i2works.smartluolong.utils.entity.Result;
import com.i2works.smartluolong.utils.exception.ServiceException;
import com.i2works.smartluolong.web.entity.Implement.ImplementDO;
import com.i2works.smartluolong.web.entity.Implement.ImplementFilesDO;
import com.i2works.smartluolong.web.entity.Implement.ImplementFilesQuery;
import com.i2works.smartluolong.web.entity.Implement.ImplementQuery;
import com.i2works.smartluolong.web.entity.item.ItemApasinfoDO;
import com.i2works.smartluolong.web.entity.item.ItemApasinfoQuery;
import com.i2works.smartluolong.web.entity.item.ItemAttrDO;
import com.i2works.smartluolong.web.entity.item.ItemNodeDO;
import com.i2works.smartluolong.web.entity.item.ItemNodeQuery;
import com.i2works.smartluolong.web.entity.user.UserAccountExtendDO;
import com.i2works.smartluolong.web.entity.user.UserAccountExtendQuery;
import com.i2works.smartluolong.web.service.implement.IImplementFilesService;
import com.i2works.smartluolong.web.service.implement.IImplementService;
import com.i2works.smartluolong.web.service.item.IItemApasinfoService;
import com.i2works.smartluolong.web.service.item.IItemAttrService;
import com.i2works.smartluolong.web.service.item.IItemNodeService;
import com.i2works.smartluolong.web.service.user.IUserAccountExtendService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Random;
/**
 * 统一申报
 *
 * @author Li haoyu
 * @date 2018/12/21
 * */
@Controller
@RequestMapping({"/unifyDeclares"})
public class UnifyDeclareController extends BaseModule {
	 private IImplementService implementService;
	  private IImplementFilesService implementFilesService;
	  private IUserAccountExtendService userAccountExtendService;
	  private IItemApasinfoService  itemApasinfoService;
	  private IItemAttrService itemAttrService;
	  private IItemNodeService  itemNodeService;

	  @Autowired
	  public UnifyDeclareController(
			  IImplementService implementService, 
			  IImplementFilesService implementFilesService, 
			  IUserAccountExtendService userAccountExtendService,
			  IItemApasinfoService  itemApasinfoService,
			  IItemAttrService itemAttrService,
			  IItemNodeService  itemNodeService)
	  {
	    this.implementService = implementService;
	    this.implementFilesService = implementFilesService;
	    this.userAccountExtendService = userAccountExtendService;
	    this.itemApasinfoService=itemApasinfoService;
	    this.itemAttrService=itemAttrService;
	    this.itemNodeService=itemNodeService;
	  }
    /**
     * 事项信息
     * */
    @GetMapping({"/info/{serviceCode}"})
    @ResponseBody
    public Result transact(@PathVariable("serviceCode") String serviceCode){
        JSONObject jsonObject=new JSONObject();
        try
        {
            ImplementQuery query = new ImplementQuery();
            query.setServiceCode(serviceCode);
            ImplementDO item = implementService.query(query);
            jsonObject.put("item", item);
            ImplementFilesQuery filesQuery = new ImplementFilesQuery();
            filesQuery.setServiceId(item.getUnid());
            List<ImplementFilesDO> filesList = implementFilesService.queryList(filesQuery);
            jsonObject.put("filesList", filesList);
            return R.success(jsonObject);
        } catch (ServiceException e) {
            e.printStackTrace();
            return R.error();
        }
    }
    /**
     * 获取办理此事项所需要填写的内容和资料
     *
     */
    @GetMapping({"/handle/{serviceCode}"})
    @ResponseBody
    public Result handle(@PathVariable("serviceCode") String serviceCode){
        JSONObject jsonObject=new JSONObject();
        try
        {
            ImplementQuery query = new ImplementQuery();
            query.setServiceCode(serviceCode);
            ImplementDO item = implementService.query(query);
            jsonObject.put("item", item);
            ImplementFilesQuery filesQuery = new ImplementFilesQuery();
            filesQuery.setServiceId(item.getUnid());
            List<ImplementFilesDO> filesList = implementFilesService.queryList(filesQuery);
            jsonObject.put("filesList", filesList);
            UserAccountExtendQuery userExtendQuery = new UserAccountExtendQuery();
            userExtendQuery.setUserId(getUserId());
            UserAccountExtendDO userExtend = userAccountExtendService.query(userExtendQuery);
            jsonObject.put("user", getLoginUser());
            jsonObject.put("userExtend", userExtend);
            return R.success(jsonObject);
        } catch (ServiceException e) {
            logger.error(e.getMessage());
            return R.error();
        }
    }
    /**
     * 申报
     * */
    @PostMapping({"/handle/save"})
    @ResponseBody
    public Result save(ItemApasinfoDO apasinfo){
        String projectId=null;
        try
        {
        	projectId=createProjectId(apasinfo.getDeptCode());
        	apasinfo.setProjId(projectId);
        	apasinfo.setProjPwd(createProjectPWD());
        	apasinfo.setApplyCardType("身份证");
        	apasinfo.setContactManCardType("身份证");
        	apasinfo.setApplyFrom("政务服务网");
        	apasinfo.setReceiveTime(new Date());
        	apasinfo.setHandleState("收件");//办理状态
        	apasinfo.setAreaCode("410311");
        	apasinfo.setDataVersion(1);
        	apasinfo.setFlowXml(getFlowXML(apasinfo));//流程xml
        	apasinfo.setSyncStatus("I");
        	String belongSystem = apasinfo.getAreaCode()+apasinfo.getDeptCode()+"001";
        	apasinfo.setBelongSystem(belongSystem);
        	apasinfo.setCreateName(apasinfo.getApplyName());
        	apasinfo.setUpdateName(apasinfo.getApplyName());
        	saveAttr(apasinfo.getAttrList(),apasinfo.getProjId());
    		 ItemNodeDO  itemNode=new ItemNodeDO();
    		 itemNode.setProjId(apasinfo.getProjId());
             itemNode.setAction(apasinfo.getHandleState());
             itemNode.setOpinion("电子件已接收");
             itemNode.setNodeName("收件");
             itemNode.setName(getUserName());
             itemNode.setStartTime(new Date());
             itemNode.setEndTime(new Date());
             itemNode.setBelongSystem(apasinfo.getBelongSystem());
             itemNode.setCreateTime(new Date());
             itemNode.setDataVersion(1);
             itemNode.setNextNodeName("受理");
             itemNode.setAreaCode(apasinfo.getAreaCode());
             itemNode.setHanderDeptId(apasinfo.getDeptCode());
             itemNode.setHanderDeptName(apasinfo.getDeptName());
             itemNode.setPhaseName("申报阶段");
             itemNode.setPhaseCode("01");
             itemNode.setSyncStatus("I");
    		 itemNodeService.save(itemNode);
    		 itemApasinfoService.save(apasinfo);
        } catch (ServiceException e) {
            logger.error(e.getMessage());
            return R.error();
        }
        return R.success(projectId);
    }
    /**
     *申报告知
     * */
    @GetMapping({"/receipt/{projectId}"})
    @ResponseBody
    public Result receipt(@PathVariable("projectId") String projectId){
        JSONObject jsonObject=new JSONObject();
        try
        {
            ItemApasinfoQuery query = new ItemApasinfoQuery();
            query.setProjId(projectId);
            ItemApasinfoDO apasinfo =itemApasinfoService.query(query);
            jsonObject.put("apasinfo", apasinfo);
            ImplementQuery impQuery = new ImplementQuery();
            impQuery.setServiceCode(apasinfo.getServiceCode());
            impQuery.setStatus("Y");
            ImplementDO item =implementService.query(impQuery);
            jsonObject.put("item", item);
            return R.success(jsonObject);
        } catch (ServiceException e) {
            logger.error(e.getMessage());
           return R.error();
        }
    }

    /**
     * 处理附件
     *
     */
    private void saveAttr(List<String> attrList,String projectId) throws ServiceException {
        if (CollectionUtils.isNotEmpty(attrList)) {
            //删除附件(通过项目ID删除)
            itemAttrService.deleteByProjectId(projectId);
            //添加附件
            for (String attr : attrList) {
                String[] str=  attr.split("##");
                //判断url是否存在
                String url = StringUtils.isNotBlank(str[0]) ? str[0] : GlobalConstant.NOPIC;
                //判断文件名是否存在
                String fileName = StringUtils.isNotBlank(str[1]) ? str[1] : "未命名";
                //判断附件名是否存在
                String attrName = StringUtils.isNotBlank(str[2]) ? str[2] : "材料";
                //写入文件
                ItemAttrDO attrDO = new ItemAttrDO();
                attrDO.setCreateName(getUserName());
                attrDO.setProjId(projectId);
                attrDO.setAttrName(attrName);
                attrDO.setFileUrl(url);
                attrDO.setFileName(fileName);
                itemAttrService.save(attrDO);
            }
        }
    }


    /**
     * 
     * 生成办件编号
     * */
    private String createProjectId(String deptCode) {
  	  String projId=null;
  	  int num=1;
  	  try {
  		  int length=deptCode.length();
  		  String applyDate = DateUtils.get(new Date(), DateConstant.YYMMDD);
  		  ItemApasinfoQuery query=new ItemApasinfoQuery();
  		  query.setReceiveTime(DateUtils.str2Date(applyDate, DateConstant.YYMMDD));
  		  query.setDeptCode(deptCode);
  		  num = itemApasinfoService.queryCount(query);
  		  num=num+1;
  		  projId = "410311" +deptCode.substring(length-3)+ applyDate + '1' + String.format("%06d", num);
  	  } catch (ServiceException e) {
  		  e.printStackTrace();
  	  }
  	  return projId;
    }
    /**
     * 生成查询密码
     *
     * */
    private static String createProjectPWD() {
        String sources = "0123456789";
        Random rand = new Random();
        StringBuffer flag = new StringBuffer();
        for (int j = 0; j < 6; j++)
        {
            flag.append(sources.charAt(rand.nextInt(9))+ "");
        }
        return flag.toString();
    }
    
    /**
     * 生成流程XML
     */
    private String getFlowXML(ItemApasinfoDO apasinfoDO) {
            String xml = "<?xml version=\"1.0\" encoding=\"GBK\"?>\r\n<NODES>\r\n";
            try {
            List<ItemNodeDO> list=Lists.newArrayList();
            ItemNodeQuery query=new ItemNodeQuery();
            query.setProjId(apasinfoDO.getProjId());
            query.setOrder(0);
            Integer	count = itemNodeService.queryCount(query);
            if(count>0) {
          	  list=itemNodeService.queryList(query);
          	  int step=1;
          	  for (ItemNodeDO itemNodeDO : list) {
                    xml += "<NODE>\r\n" +
                            "    <NODENAME>"+itemNodeDO.getNodeName()+"</NODENAME>\r\n" +
                            "    <STEP>"+step+"</STEP>\r\n" +
                            "    <STATE>"+(4-step)+"</STATE>\r\n" +
                            "    <TIMELIMIT>"+apasinfoDO.getPromiseDays()+"</TIMELIMIT>\r\n"+
                            "    <STARTTIME>"+DateUtils.get(itemNodeDO.getStartTime(), DateConstant.ALL)+"</STARTTIME>\r\n"+
                            "    <ENDTIME>"+DateUtils.get(itemNodeDO.getEndTime(), DateConstant.ALL)+"</ENDTIME>\r\n"+
                            "    <STAYTIME>0</STAYTIME>\r\n"+
                            "    <OPINION>" + itemNodeDO.getOpinion() + "</OPINION>\r\n" +
                            "    <NAME>"+itemNodeDO.getName()+"</NAME>\r\n" +
                            "    <TEL>"+apasinfoDO.getPhone()+"</TEL>\r\n" +
                            "</NODE>\r\n";
                    step++;
  			  }
            }
            xml += "</NODES>";
  		} catch (ServiceException e) {
  			e.printStackTrace();
  		}
        return xml;
    }
    
}
